package com.tanhua.dubbo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.MovementTimeLine;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

@Component
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public void saveTimeLine(Long userId, ObjectId movementId){
        //查询当前用户的好友信息
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = new Query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //遍历这些好友，将数据存入数据库中
        for (Friend friend : friends) {
            //创建好友时间线表
            MovementTimeLine movementTimeLine = new MovementTimeLine();
            //设置动态id
            movementTimeLine.setMovementId(movementId);
            //发布动态用户id
            movementTimeLine.setUserId(friend.getUserId());
            // 可见好友id
            movementTimeLine.setFriendId(friend.getFriendId());
            //发布的时间
            movementTimeLine.setCreated(System.currentTimeMillis());
            //将时间表保存到数据库中
            mongoTemplate.save(movementTimeLine);
        }
    }
}
